
package cn.javaxc.mvcwork.framework.servlets;
import cn.javaxc.mvcwork.controller.MVCConfig;
import cn.javaxc.mvcwork.framework.actions.TActionContext;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;





public class FolderGraphServlet extends HttpServlet {
	public final static String fs = System.getProperty("file.separator");
    
    public void doGet(TActionContext context)
            throws ServletException, IOException {
        //NOTE: How secure is this servlet?
        HttpServletRequest request = context.getRequest();
        HttpServletResponse response = context.getResponse();

        FileInputStream folderGraphInStream = null;
        ServletOutputStream folderGraphOutStream = null;
        String fileName = getPath(context) + "graphs" + fs + request.getParameter("GraphFileName") + ".jpg";
        
        try {
            File folderGraphFile = new File(fileName);
            if (folderGraphFile.exists()) {
                response.setContentLength((int) folderGraphFile.length());
                response.setContentType("image/jpg");

                folderGraphInStream = new FileInputStream(folderGraphFile);
                folderGraphOutStream = response.getOutputStream();

                byte[] folderGraphBuf = new byte[1024];
                int count = 0;
                while ((count = folderGraphInStream.read(folderGraphBuf)) >= 0) {
                    folderGraphOutStream.write(folderGraphBuf, 0, count);
                }
            } else {
                System.out.println("FolderGraph Servlet -> File Not Found");
            }
        } catch (IOException ioe) {
            System.out.println("Exception in FolderGraph Servlet");
            ioe.printStackTrace();
        } finally {
            folderGraphOutStream.flush();
            folderGraphInStream.close();
            folderGraphOutStream.close();
        }
    }
	protected String getPath(TActionContext context) {
    MVCConfig prefs = (MVCConfig) context.getServletContext().getAttribute("mvc");
    return prefs.get("FILELIBRARY");
  }

}
